package org.spider.api.utils.io;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件创建，工作目录+flow_id+logs+task_id
 * 如果工作目录+flow_id这个目录不存在就创建，然后<br>
 */
@Slf4j
public class FileUtils {

    public static OutputStream createLog(String directory, String flow_id, String task_id) {
        return createLog(directory, flow_id, task_id, "log");
    }

    public static OutputStream createLog(String directory, String flow_id, String task_id, String fileType) {
        OutputStream os;
        directory = directory + File.separator + flow_id + File.separator + "logs";
        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File newLog = new File(directory, task_id + "." + fileType);
        log.info("创建文件:" + newLog.getAbsolutePath());
        try {
            os = new FileOutputStream(newLog, true);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return os;
    }

    public static boolean deleteLog(String directory, String flow_id, String task_id) {
        try {
            File file = new File(directory, flow_id + File.separator + "logs" + File.separator + task_id + ".log");
            if (!file.exists()) {
                throw new FileNotFoundException();
            }
            return file.delete();
        } catch (Exception e) {
            return false;
        }
    }


    public static void appendLog(OutputStream os, String log) {
        try {
            os.write(log.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<String> readLogs(String path) {
        File log = new File(path);
        List<String> res = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(log));
            String line = null;
            while ((line = reader.readLine()) != null) {
                res.add(line);
                line = null;
            }
            //close
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    public static List<String> readLogs(String directory, String flow_id, Integer task_id) {
        File log = getLogFile(directory, flow_id, task_id);
        return readLogs(log.getAbsolutePath());
    }

    public static String readContent(String path) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line = null;
        while ((line = br.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }


    /**
     * 如果附件存在则在原文件名基础上加1 例 1（1）.txt
     * @param path     文件存放路径
     * @param fileName 文件名
     * @param suffix 文件后缀
     * @param index    当前下标 初次调用传入0
     * @return 返回file
     */
    public static File buildFileName(String path, String fileName, String suffix, Integer index) {
        File file;
        //下标不等于0开始拼后缀
        if (index != 0) {
            file = new File(path , fileName + "(" + index + ")" + suffix);
        } else {
            file = new File(path , fileName + suffix);
        }
        //判断文件是否存在 文件不存在退出递归
        if (file.isFile()) {
            //每次递归给下标加1
            file = buildFileName(path, fileName, suffix, ++index);
        }
        return file;
    }

    public static File getLogFile(String directory, String flow_id, Integer task_id) {
        File log = new File(directory, flow_id + File.separator + "logs" + File.separator + task_id + ".log");
        return log;
    }


        public static void main(String[] args) {
        String absPath = "F:\\Code\\FinalDesign\\spider\\log\\spider.log";
        List<String> logs = readLogs(absPath);
        logs.forEach(System.out::println);

    }
//    public static void main(String[] args) {
//        int n=10;
//        int a[]=new int[n+1];
//        a[0] = 1;
//        System.out.println(a[0]);
//        for(int i=1;i<=n;i++){
//            for(int j=i;j>0;j--){
//                a[j] = a[j]+a[j-1];
//            }
//            for(int j=0;j<=i;j++){
//                System.out.print(a[j]+" ");
//            }
//            System.out.println();
//        }
//    }
}
